package com.lingyuan.auth.controller;

import com.alibaba.fastjson.JSON;
import com.lingyuan.auth.form.LoginBody;
import com.lingyuan.auth.form.RegisterBody;
import com.lingyuan.auth.service.SysLoginService;
import com.lingyuan.auth.service.UmsLoginService;
import com.lingyuan.common.core.constant.CacheConstants;
import com.lingyuan.common.core.domain.R;
import com.lingyuan.common.core.domain.vo.ums.MemberLogin;
import com.lingyuan.common.core.domain.vo.ums.MemberVo;
import com.lingyuan.common.core.utils.JwtUtils;
import com.lingyuan.common.core.utils.StringUtils;
import com.lingyuan.common.security.auth.AuthUtil;
import com.lingyuan.common.security.service.TokenService;
import com.lingyuan.common.security.utils.SecurityUtils;
import com.lingyuan.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("memberAuth")
public class LoginPcController
{
    @Autowired
    private UmsLoginService umsLoginService;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("login")
    public R<MemberLogin> login(@RequestBody LoginBody form)
    {
        // 用户登录
        MemberLogin login = umsLoginService.login(form);
        // 获取登录token
        return R.ok(login);
    }

    @PostMapping("logout")
    public R logout()
    {
        String token = request.getHeader("token");
        String userKey = JwtUtils.getUserKey(token);
        stringRedisTemplate.delete(CacheConstants.LOGIN_TOKEN_KEY + userKey);
        return R.ok();
    }

    @GetMapping("info")
    public R<MemberVo> info()
    {
        String token = request.getHeader("token");
        String userKey = JwtUtils.getUserKey(token);
        String memberStr = stringRedisTemplate.opsForValue().get(CacheConstants.LOGIN_TOKEN_KEY + userKey);
        return R.ok(JSON.parseObject(memberStr,MemberVo.class));
    }


}
